package hot100;

public class Lc142 {
    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public ListNode detectCycle(ListNode head) {
        if (head == null) return null;
        ListNode slow = head;
        ListNode fast = head;
        ListNode check = null;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                check = slow;
                break;
            }
        }
        if (check == null) {
            return null;
        }

        ListNode detect = head;
        while (detect != slow) {
            detect = detect.next;
            slow = slow.next;
        }
        return detect;
    }
}
